package se.lth.eit.eit060.proj2.client;

import java.io.*;
import java.net.UnknownHostException;
import javax.net.ssl.*;
import javax.security.cert.X509Certificate;

import se.lth.eit.eit060.proj2.initiation.Utility;
import se.lth.eit.eit060.proj2.server.Logger;

public class MyClient extends Thread {

	private String host;
	private SSLContext ctx;

	private String record;
	private String action;
	private String myPassword;

	private MyPanel mp;

	public MyClient(String host, MyPanel mp) {
		this.host = host;
		this.mp = mp;
	}

	public void run() {
		SSLSocket socket;
		try {
			SSLSocketFactory factory = ctx.getSocketFactory();
			socket = (SSLSocket) factory.createSocket(host, Utility.PORT);
			InputStream inputstream = System.in;
			InputStreamReader inputstreamreader = new InputStreamReader(
					inputstream);
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			String userInput = null;
			
			SSLSession session = socket.getSession();
			X509Certificate crt = null;
			try {
				crt = (X509Certificate) session.getPeerCertificateChain()[0];
			} catch (SSLPeerUnverifiedException e1) {
				System.out.println("ERROR IN MyClient, ABORTS. No certificate!");
				return;
			}
			String name = null;
			try{
				name = crt.getSubjectDN().getName().split("=")[1].split(",")[0];
			}catch(Exception e){
				System.out.println("Identification error.");
				return; //Should be break later.
			}
			if(!name.equals("server")){
				System.out.println("THIS ISN'T THE SERVER YOU ARE LOOKING FOR!");
				return;
			}

			
			/*
			 * BufferedReader stdIn = new BufferedReader( new
			 * InputStreamReader(System.in));
			 */
			while (true) {
				String text = checkWait();
				//System.out.println(action);
				System.out.println(text);
				out.println(action + Utility.SPLIT + record +"<>" + myPassword + Utility.SPLIT
						+ text);
				parse(in.readLine());
				clear();
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			mp.setTitle("Connection refused.");
			e.printStackTrace();
		}
	}

	private void parse(String s) {
		String[] orders = s.split(Utility.SPLIT);
		System.out.println("MyClient: "+s);
		if (orders != null && orders.length > 0) {
			if (orders[0].equals(Utility.LIST)) {
				orders[0] = null;
				mp.setList(orders);
			}else if(orders[0].equals(Utility.READ)){
				orders[0]="";
				mp.setText(orders);
			}else{
				mp.setTitle(s.substring(orders[0].length()+Utility.SPLIT.length()));
			}
		}
	}

	private synchronized String checkWait() {
		while (action == null) {
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if(action.equals(Utility.CREATE)){
			System.out.println(mp.getText());
			return mp.getText().replace(""+Logger.n,Utility.SPLIT);
		}else if(action.equals(Utility.UPDATE)){
			System.out.println(mp.getText());
			return mp.getText().replace(""+Logger.n,Utility.SPLIT);
		}
		return "";
	}

	public void login(String keystore, char[] password) {
		ctx = Utility.generate(keystore, password);
	}

	private void clear() {
		record = null;
		action = null;
		myPassword = null;
	}

	public void setActions(String record, String action,String myPassword) {
		this.record = record;
		this.action = action;
		this.myPassword = myPassword;
	}

}
